package org.qpcr.community.device.service;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.qpcr.community.device.entity.TemperatureCalibrationMetricEntity;
import org.qpcr.community.device.web.request.TemperatureCalibrationMetricEditRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class TemperatureCalibrationMetricService extends GenericReactiveCrudService<TemperatureCalibrationMetricEntity, String> {

    public Mono<Integer> edit(TemperatureCalibrationMetricEditRequest req) {
        if (req == null || req.getData() == null || req.getData().isEmpty()) {
            return Mono.just(0);
        }
        // 只更新有id和value的项
        List<TemperatureCalibrationMetricEditRequest.EditData> validList = req.getData().stream()
                .filter(e -> e.getId() != null && e.getValue() != null)
                .collect(Collectors.toList());
        if (validList.isEmpty()) {
            return Mono.just(0);
        }
        // 批量更新，每个id对应一个value
        return Flux.fromIterable(validList)
                .flatMap(editData -> createUpdate()
                        .set(TemperatureCalibrationMetricEntity::getValue, editData.getValue())
                        .is(TemperatureCalibrationMetricEntity::getId, editData.getId())
                        .execute())
                .reduce(Integer::sum)
                .defaultIfEmpty(0);
    }

    public Mono<List<TemperatureCalibrationMetricEntity>> list() {
        return createQuery().fetch().collectList();
    }
}
